package cn.lysj.framework.pirpraph.controller;

import cn.lysj.framework.common.annotation.CurrentUser;
import cn.lysj.framework.common.domain.User;
import cn.lysj.framework.common.utils.random.FormatUtil;
import cn.lysj.framework.common.utils.format.FormatObject;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.common.utils.web.Resp;
import cn.lysj.framework.elm.domain.ElmOrder;
import cn.lysj.framework.elm.elmenum.ElmOrderStatus;
import cn.lysj.framework.elm.service.ElmOrderService;
import cn.lysj.framework.foodv2.domain.FoodType;
import cn.lysj.framework.foodv2.service.FoodTypeService;
import cn.lysj.framework.order.domain.FoodOrder;
import cn.lysj.framework.order.domain.FoodOrderInfo;
import cn.lysj.framework.order.service.FoodOrderInfoService;
import cn.lysj.framework.order.service.FoodOrderService;
import cn.lysj.framework.pirpraph.vo.DayBusinessStatis;
import cn.lysj.framework.pirpraph.service.PirPraphService;
import cn.lysj.framework.pirpraph.vo.DayFoodTypeStatis;
import cn.lysj.framework.pirpraph.vo.DayOrderNum;
import cn.lysj.framework.pirpraph.vo.DayPayStatis;
import io.swagger.annotations.Api;
import javafx.scene.input.InputMethodTextRun;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zwj
 * @description 订单控制层
 * @create 2018-11-05 09:51:42
 **/
@Slf4j
@RestController
@Api(description = "统计报表管理接口")
@RequestMapping("/pir_praph")
public class PirPraphController {

    @Resource
    private PirPraphService pirPraphService;

    @Resource
    private FoodOrderService foodOrderService;

    @Resource
    private ElmOrderService elmOrderService;

    @Resource
    private FoodOrderInfoService foodOrderInfoService;

    @Resource
    private FoodTypeService foodTypeService;

    @Resource
    private EntityManager entityManager;

    @GetMapping("/get_pir_praph")
    public Resp test(@CurrentUser User user, Integer type, Integer number) {
        return pirPraphService.getPirPraphVo(user.getStoreId(), type, number);
    }

    /*
     * @author drj
     * @date 2019-02-25 18:07
     * @Description :财务管理
     */
    @GetMapping("/financial_manage")
    public Resp financialManage(@CurrentUser User user) {
        Map<String, Object> map = new HashMap<>();
        //订单数量(已结单)
        Integer totalOrder = foodOrderService.getRepository().countByStoreIdAndFoodOrderStatus(user.getStoreId(),2);
        //现金收入
        BigDecimal cashMoney = foodOrderService.getRepository().summaryMoney(user.getStoreId(), 2);
        //支付收入
        BigDecimal payMoney = foodOrderService.getRepository().summaryMoney(user.getStoreId(), 1);
        map.put("totalOrder", totalOrder);
        map.put("cashMoney", FormatObject.formatZero(cashMoney));
        map.put("payMoney", FormatObject.formatZero(payMoney));
        return new Resp(map);
    }

    /*
     * @author drj
     * @date 2019-02-25 18:07
     * @Description ：日收银统计
     */
    @GetMapping("/day_summary_cashier")
    public Resp daySummaryCashier(@CurrentUser User user, Date createDate) {
        Map<String, Object> map = new HashMap<>();
        //线下支付金额
        List<Object[]> daySummaryOffCashier = foodOrderService.getRepository().daySummaryOffCashier(user.getStoreId(), createDate, FormatUtil.getDayEndDay(createDate));
        //线上微信支付
        List<Object[]> daySummaryWeCashier = foodOrderService.getRepository().daySummaryOnLineCashier(user.getStoreId(), 2, createDate, FormatUtil.getDayEndDay(createDate));
        //线上支付宝支付
        List<Object[]> daySummaryAliCashier = foodOrderService.getRepository().daySummaryOnLineCashier(user.getStoreId(), 1, createDate, FormatUtil.getDayEndDay(createDate));

        map.put("daySummaryOffCashier", FormatObject.formatZero(daySummaryOffCashier.size() == 0 ? BigDecimal.ZERO : (BigDecimal) daySummaryOffCashier.get(0)[1]));
        map.put("daySummaryWeCashier", FormatObject.formatZero(daySummaryWeCashier.size() == 0 ? BigDecimal.ZERO : (BigDecimal) daySummaryWeCashier.get(0)[1]));
        map.put("daySummaryAliCashier", FormatObject.formatZero(daySummaryAliCashier.size() == 0 ? BigDecimal.ZERO : (BigDecimal) daySummaryAliCashier.get(0)[1]));
        return new Resp(map);
    }


    /*
     * @author drj
     * @date 2019-02-25 18:06
     * @Description ：日营业统计
     */
    @GetMapping("/day_summary_business")
    public Resp daySummaryBusiness(@CurrentUser User user, Date createDate) {
        StringBuilder sb = new StringBuilder();
        List<Object> par = new ArrayList<>();
        sb.append("select new cn.lysj.framework.pirpraph.vo.DayBusinessStatis(sum(discountMoney) as discountMoney," +
                " sum(actPayMoney) as actPayMoney ,count(id) as orderNum ,SUM(useFoodNumber)  as  useFoodNumber ) from FoodOrder WHERE foodOrderStatus=2 AND storeId= ?");
        if (createDate != null) {
            Date endDate = FormatUtil.getDayEndDay(createDate);
            sb.append(" and createTime >= ? and createTime <= ?");
            par.add(createDate);
            par.add(endDate);
        }
        Query query = entityManager.createQuery(sb.toString(), DayBusinessStatis.class);
        query.setParameter(1, user.getStoreId());
        for (int i = 0; i < par.size(); i++) {
            query.setParameter(i + 2, par.get(i));
        }
        DayBusinessStatis dayBusinessStatis = (DayBusinessStatis) query.getSingleResult();
        //格式化数据
        FormatObject.format(dayBusinessStatis, 2);
        return new Resp(dayBusinessStatis);
    }

    /*
     * @author drj
     * @date 2019-02-25 22:50
     * @Description ：订单汇总表
     */
    @GetMapping("/day_summary_order")
    public Resp daySummaryOrder(@CurrentUser User user, Date begin_date, Date end_date) {
        Map<Object, DayOrderNum> map = new HashMap<>();
        //堂食订单
        List<Object[]> eatObjects = foodOrderService.getRepository().
                platOrderNum(user.getStoreId(), 1, begin_date, FormatUtil.getDayEndDay(end_date));
        for (Object[] object : eatObjects) {
            DayOrderNum dayOrderNum = new DayOrderNum();
            dayOrderNum.setEatNumber((BigInteger) object[1]);
            map.put(object[0], dayOrderNum);
        }
        //外带订单
        List<Object[]> outSideObjects = foodOrderService.getRepository().
                platOrderNum(user.getStoreId(), 2, begin_date, FormatUtil.getDayEndDay(end_date));
        for (Object[] outSideObject : outSideObjects) {
            if (map.containsKey(outSideObject[0])) {
                DayOrderNum dayOrderNum = (DayOrderNum) map.get(outSideObject[0]);
                dayOrderNum.setBesideNumber((BigInteger) outSideObject[1]);
                map.put(outSideObject[0], dayOrderNum);
            } else {
                DayOrderNum dayOrderNum = new DayOrderNum();
                dayOrderNum.setBesideNumber((BigInteger) outSideObject[1]);
                map.put(outSideObject[0], dayOrderNum);
            }
        }
        //饿了么订单
        List<Object[]> elmObjects = elmOrderService.getRepository().
                elmOrderNum(user.getStoreId(), begin_date, FormatUtil.getDayEndDay(end_date));
        for (Object[] outSideObject : elmObjects) {
            if (map.containsKey(outSideObject[0])) {
                DayOrderNum dayOrderNum = (DayOrderNum) map.get(outSideObject[0]);
                dayOrderNum.setWaimaiNumber((BigInteger) outSideObject[1]);
                map.put(outSideObject[0], dayOrderNum);
            } else {
                DayOrderNum dayOrderNum = new DayOrderNum();
                dayOrderNum.setWaimaiNumber((BigInteger) outSideObject[1]);
                map.put(outSideObject[0], dayOrderNum);
            }
        }
        //将map转为list
        List<DayOrderNum> dayOrderNums = new LinkedList<>();
        for (Object o : map.keySet()) {
            DayOrderNum dayOrderNum = (DayOrderNum) map.get(o);
            dayOrderNum.setDate(String.valueOf(o));
            FormatObject.format(dayOrderNum, 2);
            dayOrderNums.add(dayOrderNum);
        }
        //对返回结果的日期进行排序
        dayOrderNums = dayOrderNums.stream().sorted(Comparator.comparing(DayOrderNum::getDate)).collect(Collectors.toList());
        return new Resp(dayOrderNums);
    }

    /*
     * @author drj
     * @date 2019-02-26 17:36
     * @Description :支付方式
     */
    @GetMapping("/pay_way_statis")
    public Resp payWayStatis(@CurrentUser User user, Date begin_date, Date end_date) {
        Map<Object, DayPayStatis> map = new HashMap<>();
        //线下支付金额
        List<Object[]> daySummaryOffCashier = foodOrderService.getRepository().
                daySummaryOffCashier(user.getStoreId(), begin_date, FormatUtil.getDayEndDay(end_date));
        for (Object[] object : daySummaryOffCashier) {
            DayPayStatis dayPayStatis = new DayPayStatis();
            dayPayStatis.setOffCashier((BigDecimal) object[1]);
            map.put(object[0], dayPayStatis);
        }
        //线上微信支付
        List<Object[]> daySummaryWeCashier = foodOrderService.getRepository().
                daySummaryOnLineCashier(user.getStoreId(), 2, begin_date, FormatUtil.getDayEndDay(end_date));
        for (Object[] dayWePay : daySummaryWeCashier) {
            if (map.containsKey(dayWePay[0])) {
                DayPayStatis dayPayStatis = (DayPayStatis) map.get(dayWePay[0]);
                dayPayStatis.setWeCashier((BigDecimal) dayWePay[1]);
                map.put(dayWePay[0], dayPayStatis);
            } else {
                DayPayStatis dayPayStatis = new DayPayStatis();
                dayPayStatis.setWeCashier((BigDecimal) dayWePay[1]);
                map.put(dayWePay[0], dayPayStatis);
            }
        }
        //线上支付宝支付
        List<Object[]> daySummaryAliCashier = foodOrderService.getRepository().
                daySummaryOnLineCashier(user.getStoreId(), 1, begin_date, FormatUtil.getDayEndDay(end_date));
        for (Object[] dayWePay : daySummaryAliCashier) {
            if (map.containsKey(dayWePay[0])) {
                DayPayStatis dayPayStatis = (DayPayStatis) map.get(dayWePay[0]);
                dayPayStatis.setAliCashier((BigDecimal) dayWePay[1]);
                map.put(dayWePay[0], dayPayStatis);
            } else {
                DayPayStatis dayPayStatis = new DayPayStatis();
                dayPayStatis.setAliCashier((BigDecimal) dayWePay[1]);
                map.put(dayWePay[0], dayPayStatis);
            }
        }
        //将map转为list
        List<DayPayStatis> dayPayStatisList = new LinkedList<>();
        for (Object o : map.keySet()) {
            DayPayStatis dayPayStatis = (DayPayStatis) map.get(o);
            dayPayStatis.setDate(String.valueOf(o));
            FormatObject.format(dayPayStatis, 2);
            dayPayStatisList.add(dayPayStatis);
        }
        //对返回结果的日期进行排序
        dayPayStatisList = dayPayStatisList.stream().sorted(Comparator.comparing(DayPayStatis::getDate)).collect(Collectors.toList());
        return new Resp(dayPayStatisList);
    }

    /*
     * @author drj
     * @date 2019-02-26 21:25
     * @Description :菜品类型
     */
    @GetMapping("/food_type_statis")
    public Resp foodTypeStatis(@CurrentUser User user, Date begin_date, Date end_date) {
        Map<String, DayFoodTypeStatis> map = new HashMap<>();
        List<FoodOrder> foodOrderList = foodOrderService.getRepository().
                findByStoreIdAndFoodOrderStatusAndCreateTimeBetween(user.getStoreId(), 2,begin_date, FormatUtil.getDayEndDay(end_date));
        for (FoodOrder foodOrder : foodOrderList) {
            List<FoodOrderInfo> foodOrderInfoList = foodOrderInfoService.getRepository().
                    findByFoodOrderId(foodOrder.getId());
            for (FoodOrderInfo foodOrderInfo : foodOrderInfoList) {
                if (map.containsKey(foodOrderInfo.getFoodTypeId())) {
                    DayFoodTypeStatis dayFoodTypeStatis = (DayFoodTypeStatis) map.get(foodOrderInfo.getFoodTypeId());
                    dayFoodTypeStatis.setMoney(map.get(foodOrderInfo.getFoodTypeId()).getMoney().add(foodOrderInfo.getMoney()));
                    dayFoodTypeStatis.setNumber(map.get(foodOrderInfo.getFoodTypeId()).getNumber() + foodOrderInfo.getNumber());
                } else {
                    DayFoodTypeStatis dayFoodTypeStatis = new DayFoodTypeStatis();
                    dayFoodTypeStatis.setMoney(foodOrderInfo.getMoney());
                    dayFoodTypeStatis.setNumber(foodOrderInfo.getNumber());
                    map.put(foodOrderInfo.getFoodTypeId(), dayFoodTypeStatis);
                }
            }
        }
        //将map转为list
        List<DayFoodTypeStatis> dayFoodTypeStatisList = new LinkedList<>();
        for (Object o : map.keySet()) {
            DayFoodTypeStatis dayFoodTypeStatis = (DayFoodTypeStatis) map.get(o);
            FoodType foodType = foodTypeService.findOne(String.valueOf(o));
            if (!ParamUtil.isBlank(foodType)) {
                dayFoodTypeStatis.setFoodTypeName(foodType.getName());
            }
            FormatObject.format(dayFoodTypeStatis, 2);
            dayFoodTypeStatisList.add(dayFoodTypeStatis);
        }
        return new Resp(dayFoodTypeStatisList);

    }


}
